<?php

namespace app\common\model\Product;

// 引入TP基础模型
use think\Model;

// 产品模型
class  Product extends Model
{
    // 设置当前模型对应的数据表名称
    protected $name = 'product';

    protected $autoWriteTimestamp = true;

    protected $createTime = 'createtime';

    protected $updateTime = false;

    protected $append = [
        'thumbs_text', // 单张图片
        'thumbs_list', // 多张图片
        'sales_count', // 销量
        'status_text', // 状态
    ];

    // 单张图片
    public function getThumbsTextAttr($value, $data)
    {
        $url = request()->domain();

        $thumbs = !empty($data['thumbs']) ? explode(',', $data['thumbs']) : '';

        if($thumbs)
        {
            $thumbs = $url . $thumbs[0];
        }
        else
        {
            $thumbs = $url .'/assets/img/product.jpg';
        }

        return $thumbs;
    }

    // 多张图片
    public function getThumbsListAttr($value, $data)
    {
        $url = request()->domain();

        $thumbs = !empty($data['thumbs']) ? $data['thumbs'] : '';

        if($thumbs)
        {
            $thumbs = explode(',', $data['thumbs']);

            $thumb = str_ireplace("/uploads/", $url . '/uploads/', $thumbs);

            $thumbs = [
                $thumb
            ];
        }
        else
        {
            $thumbs = [
                $url .'/assets/img/product.jpg'
            ];
        }
        
        return $thumbs;
    }

    // 销量
    public function getSalesCountAttr($value, $data){
        $orderProduct = model('Product.OrderProduct');
        $count = $orderProduct->where('proid', $data['id'])->count();
        return $count;
    }

    // 商品状态
    public function getStatusTextAttr($value, $data) {
        if ($data['status'] == 1) {
            return '上架';
        } else {
            return '下架';
        }
    }

    // 商品分类
    public function type() {
        return $this->belongsTo('app\common\model\Product\Type', 'typeid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    // 商品单位
    public function unit() {
        return $this->belongsTo('app\common\model\Product\Unit', 'unitid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
